package com.campus.counseling.controller;

import com.campus.counseling.model.common.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.Files;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class FileController {

    @Value("${spring.file.upload.path}")
    private String uploadPath;

    @PostConstruct
    public void init() {
        try {
            // 使用绝对路径
            File uploadDir = new File(uploadPath).getAbsoluteFile();
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                if (!created) {
                    throw new RuntimeException("无法创建上传目录：" + uploadDir.getAbsolutePath());
                }
            }
            
            // 创建证书目录
            File certificatesDir = new File(uploadDir, "certificates");
            if (!certificatesDir.exists()) {
                boolean created = certificatesDir.mkdirs();
                if (!created) {
                    throw new RuntimeException("无法创建证书目录：" + certificatesDir.getAbsolutePath());
                }
            }

            // 创建头像目录
            File avatarsDir = new File(uploadDir, "avatars");
            if (!avatarsDir.exists()) {
                boolean created = avatarsDir.mkdirs();
                if (!created) {
                    throw new RuntimeException("无法创建头像目录：" + avatarsDir.getAbsolutePath());
                }
            }

            // 创建文章图片目录
            File articlesDir = new File(uploadDir, "articles");
            if (!articlesDir.exists()) {
                boolean created = articlesDir.mkdirs();
                if (!created) {
                    throw new RuntimeException("无法创建文章图片目录：" + articlesDir.getAbsolutePath());
                }
            }
            
            log.info("文件上传目录初始化成功：{}", uploadDir.getAbsolutePath());
        } catch (Exception e) {
            log.error("文件上传目录初始化失败", e);
            throw new RuntimeException("无法创建文件上传目录", e);
        }
    }

    @PostMapping("/certificate")
    public Result<String> uploadCertificate(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("请选择文件");
        }

        try {
            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("文件名不能为空");
            }
            
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            if (!Arrays.asList(".jpg", ".jpeg", ".png", ".pdf").contains(extension)) {
                return Result.error("只支持jpg、jpeg、png、pdf格式的文件");
            }

            // 生成新的文件名
            String newFilename = UUID.randomUUID().toString() + extension;
            
            // 使用绝对路径
            File destFile = new File(new File(uploadPath, "certificates"), newFilename).getAbsoluteFile();
            
            // 确保目标目录存在
            if (!destFile.getParentFile().exists()) {
                boolean created = destFile.getParentFile().mkdirs();
                if (!created) {
                    throw new IOException("无法创建目标目录：" + destFile.getParent());
                }
            }

            // 保存文件
            file.transferTo(destFile);
            log.info("文件上传成功：{}", destFile.getAbsolutePath());

            // 返回文件访问路径
            return Result.success("/api/file/certificates/" + newFilename);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("请选择文件");
        }

        try {
            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("文件名不能为空");
            }
            
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            if (!Arrays.asList(".jpg", ".jpeg", ".png").contains(extension)) {
                return Result.error("只支持jpg、jpeg、png格式的图片");
            }

            // 检查文件大小（2MB）
            if (file.getSize() > 2 * 1024 * 1024) {
                return Result.error("图片大小不能超过2MB");
            }

            // 生成新的文件名
            String newFilename = UUID.randomUUID().toString() + extension;
            
            // 使用绝对路径
            File destFile = new File(new File(uploadPath, "avatars"), newFilename).getAbsoluteFile();
            
            // 确保目标目录存在
            if (!destFile.getParentFile().exists()) {
                boolean created = destFile.getParentFile().mkdirs();
                if (!created) {
                    throw new IOException("无法创建目标目录：" + destFile.getParent());
                }
            }

            // 保存文件
            file.transferTo(destFile);
            log.info("头像上传成功：{}", destFile.getAbsolutePath());
            
            // 直接返回正确的API访问路径
            return Result.success("/api/file/avatars/" + newFilename);
        } catch (IOException e) {
            log.error("头像上传失败", e);
            return Result.error("头像上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/upload/article")
    public Result<String> uploadArticleImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("请选择文件");
        }

        try {
            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("文件名不能为空");
            }
            
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            if (!Arrays.asList(".jpg", ".jpeg", ".png", ".gif").contains(extension)) {
                return Result.error("只支持jpg、jpeg、png、gif格式的图片");
            }

            // 检查文件大小（5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error("图片大小不能超过5MB");
            }

            // 生成新的文件名
            String newFilename = UUID.randomUUID().toString() + extension;
            
            // 使用绝对路径
            File destFile = new File(new File(uploadPath, "articles"), newFilename).getAbsoluteFile();
            
            // 确保目标目录存在
            if (!destFile.getParentFile().exists()) {
                boolean created = destFile.getParentFile().mkdirs();
                if (!created) {
                    throw new IOException("无法创建目标目录：" + destFile.getParent());
                }
            }

            // 保存文件
            file.transferTo(destFile);
            log.info("文章图片上传成功：{}", destFile.getAbsolutePath());
            
            // 返回文件访问路径
            return Result.success("/api/file/articles/" + newFilename);
        } catch (IOException e) {
            log.error("文章图片上传失败", e);
            return Result.error("文章图片上传失败：" + e.getMessage());
        }
    }

    @GetMapping("/file/articles/{filename}")
    public void getArticleImage(@PathVariable String filename, HttpServletResponse response) throws IOException {
        File file = new File(new File(uploadPath, "articles"), filename).getAbsoluteFile();
        if (!file.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 设置内容类型
        String contentType = "image/jpeg";
        if (filename.endsWith(".png")) {
            contentType = "image/png";
        } else if (filename.endsWith(".gif")) {
            contentType = "image/gif";
        }
        response.setContentType(contentType);

        // 复制文件内容到响应输出流
        Files.copy(file.toPath(), response.getOutputStream());
        response.getOutputStream().flush();
    }
} 